﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using HandyControl.Controls;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Runtime.ConstrainedExecution;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using VisionImage.Model;
using MessageBox = HandyControl.Controls.MessageBox;

namespace VisionImage
{
    public partial class MainViewModel:ObservableObject
    {
        [ObservableProperty]
        private string barcode = string.Empty;
        SerialPort serial;

        public ObservableCollection<ImageData> ImageDataList { get; } = new ObservableCollection<ImageData>();

        [ObservableProperty]
        private string selectedImagePath = string.Empty;
        private string imageFolderPath =ConfigurationManager.AppSettings["ImageUrl"];
        public MainViewModel()
        {
            //Task.Run(() =>
            //{
            //    MonitorSerialPort();
            //});
        }
        public void MonitorSerialPort()
        {
            serial = new SerialPort();
            serial.BaudRate = 9600;
            serial.DataBits = 8;
            serial.PortName = "Com1";
            serial.StopBits = System.IO.Ports.StopBits.One;
            serial.Parity = System.IO.Ports.Parity.None;
            serial.ReadTimeout = 100;
            serial.Open();
            if (!serial.IsOpen)
            {
                MessageBox.Show("端口打开失败");
                return;
            }
            else
            {
            }
            serial.DataReceived += ser_DataReceived;
        }

        private void ser_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            string receive = "";//数据接收
            try
            {
                Thread.Sleep(50);    
                int len = serial.BytesToRead;
                if (len != 0)
                {
                    byte[] buff = new byte[len];
                    serial.Read(buff, 0, len);
                    receive = Encoding.Default.GetString(buff);
                    Barcode = receive;
                    SearchByBarcode();
                }
            }
            catch
            {
                return;
            }
        }

        // 定义搜索命令
        [RelayCommand]
        private void Search()
        {
            SearchByBarcode();
        }

        private void SearchByBarcode()
        {
            string barcodeValue = Barcode;
            if (string.IsNullOrEmpty(barcodeValue))
            {
                return;
            }
            ImageDataList.Clear();
            try
            {
                if (Directory.Exists(imageFolderPath))
                {
                    string[] timeFolders = Directory.GetDirectories(imageFolderPath);

                    foreach (string timeFolder in timeFolders)
                    {
                        string[] cameraFolders = Directory.GetDirectories(timeFolder);

                        foreach (string cameraFolder in cameraFolders)
                        {
                            string[] typeFolders = Directory.GetDirectories(cameraFolder);

                            foreach (string typeFolder in typeFolders)
                            {
                                string typeName = Path.GetFileName(typeFolder);
                                string[] imageFiles = Directory.GetFiles(typeFolder);

                                foreach (string imageFile in imageFiles)
                                {
                                    if (Path.GetFileName(imageFile).Contains(barcodeValue))
                                    {
                                        string fileName = Path.GetFileName(imageFile);
                                        string cameraName = ExtractCameraName(imageFile);
                                        ImageDataList.Add(new ImageData
                                        {
                                            ImageName = fileName,
                                            ImagePath = imageFile,
                                            CameraName = cameraName,
                                            ImageType = typeName
                                        });

                                    }
                                }
                            }
                        }
                    }

                    if (ImageDataList.Count == 0)
                    {
                        // 可以通过消息服务显示消息
                       MessageBox.Show($"未找到条码为 {barcodeValue} 的图片");
                    }
                }
                else
                {
                    MessageBox.Show($"图片文件夹不存在: {imageFolderPath}");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"搜索图片时出错: {ex.Message}");
            }
        }
        private string ExtractCameraName(string filePath)
        {
            // 获取文件所在目录
            string directory = Path.GetDirectoryName(filePath);

            // 获取父目录(类型文件夹的上一级)
            string parentDirectory = Path.GetDirectoryName(directory);
            // 相机名称是相机目录的最后一层
            string cameraName = Path.GetFileName(parentDirectory);

            return cameraName;
        }
    }
}
